package com.nlx.notes.support.util;

import cn.hutool.core.util.RandomUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileUtils {


    public static void main(String[] args) throws InterruptedException {
        // ====== 可自定义参数 ======
        String dirPath = "G:\\账单\\aaa"; // 输出目录
        long totalSizeGB = 80;     // 总大小 100GB
        long fileSizeGB = 10;        // 每个文件 5GB
        int threadCount = 10;        // 使用线程数量

        generateRandomFiles(dirPath, totalSizeGB, fileSizeGB, threadCount);
    }

    public static void generateRandomFiles(String dirPath, long totalSizeGB, long fileSizeGB, int threadCount) throws InterruptedException {
        File dir = new File(dirPath);
        if (!dir.exists()) dir.mkdirs();

        long totalFiles = (long) Math.ceil((double) totalSizeGB / fileSizeGB);
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        System.out.printf("💾 开始生成随机文件，总大小: %dGB，单文件: %dGB，共: %d 个文件，线程数: %d\n",
                totalSizeGB, fileSizeGB, totalFiles, threadCount);

        for (int i = 1; i <= totalFiles; i++) {
            int index = i;
            executor.submit(() -> {
                try {
                    generateSingleFile(dirPath, index, fileSizeGB);
                } catch (IOException e) {
                    System.err.println("❌ 文件生成失败: " + e.getMessage());
                }
            });
        }

        executor.shutdown();
        while (!executor.isTerminated()) {
            Thread.sleep(1000);
        }

        System.out.println("✅ 所有随机文件生成完成！");
    }

    private static void generateSingleFile(String dirPath, int index, long fileSizeGB) throws IOException {
        long fileBytes = fileSizeGB * 1024L * 1024L * 1024L;
        int bufferSize = 4 * 1024 * 1024; // 4MB
        byte[] buffer = new byte[bufferSize];
        Random random = new Random();

        File file = new File(dirPath, RandomUtil.randomString(16) + index + ".bin");
        try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
            long written = 0;
            while (written < fileBytes) {
                random.nextBytes(buffer);
                long writeSize = Math.min(bufferSize, fileBytes - written);
                out.write(buffer, 0, (int) writeSize);
                written += writeSize;
            }
        }

        System.out.printf("线程[%s] 完成文件 %s (%.2f GB)\n",
                Thread.currentThread().getName(),
                file.getName(),
                (double) fileSizeGB);
    }

}
